// pages/story/player.js
let islxPlay
let index
let prePage
let oldRateIndex
let videoContext
Page({
  data:{
    rates:[{rate:0.5},{rate:0.8},{rate:'1.0'},{rate:1.25},{rate:1.5},{rate:'2.0'}]
  },
  setRate(e){
    let index = e.target.dataset.index
    if (index == undefined) return

    // 1)重新设置整个数组为页面数据
    // let rates = this.data.rates
    // rates[oldRateIndex].selected = false
    // rates[index].selected = true
    // this.setData({rates})
    // oldRateIndex = index

    // 2)仅仅设置要修改的数据
    // this.setData({'rates[4].selected':true})
    // this.setData({['rates['+ index +'].selected']:true})

    let change = {}
    change['rates['+ oldRateIndex +'].selected'] = false
    change['rates['+ index +'].selected'] = true
    oldRateIndex = index
    videoContext.playbackRate(+this.data.rates[oldRateIndex].rate)
    this.setData(change)
  },
  onLoad(options) {
    videoContext = wx.createVideoContext('player', this)
    oldRateIndex = wx.getStorageSync('rateIndex') || 2

    let url = decodeURIComponent(options.url || ''),title,jj
    if(url){
      islxPlay = false
      title = decodeURIComponent(options.title)
      jj = decodeURIComponent(options.jj)      
    }else{
      index = options.index
      let pages = getCurrentPages()
      prePage = pages[pages.length - 2]
      islxPlay = prePage.islxPlay
      let story = prePage.data.storys[index]
      title = story.title
      url = story.url
      jj = story.jj      
    }
    this.setData({title,url,jj,['rates['+ oldRateIndex +'].selected']:true},() => {
      videoContext.playbackRate(+this.data.rates[oldRateIndex].rate)    
    })
  },
  onUnload(){
    wx.setStorageSync('rateIndex', oldRateIndex)
  },
  next(e){
    if(islxPlay){
      if (++index < prePage.data.storys.length) {
        let story = prePage.data.storys[index]
        let title = story.title
        let url = story.url
        let jj = story.jj
        this.setData({title,url,jj},() => {
          videoContext.playbackRate(+this.data.rates[oldRateIndex].rate) 
        })
        return 
      }
    }
    wx.navigateBack()
  },
  onShareAppMessage(e){
    return{
      title: this.data.title,
      path: '/pages/story/player?title=' + encodeURIComponent(this.data.title) + '&url=' + encodeURIComponent(this.data.url) + '&jj=' + encodeURIComponent(this.data.jj)
    }
  },
  onShareTimeline(e){
    return{
      title: this.data.title,
      path: '/pages/story/player?title=' + encodeURIComponent(this.data.title) + '&url=' + encodeURIComponent(this.data.url) + '&jj=' + encodeURIComponent(this.data.jj)
    }
  },
})